using System.Web.Mvc;
using MeuDindin.Core;
using SharpArch.Core.PersistenceSupport;
using SharpArch.Core.DomainModel;
using System.Collections.Generic;
using System;
using SharpArch.Web.NHibernate;
using NHibernate.Validator.Engine;
using System.Text;
using SharpArch.Web.CommonValidator;
using SharpArch.Core;

namespace MeuDindin.Web.Controllers
{
    [HandleError]
    public class UsuariosController : Controller
    {
        public UsuariosController(IRepository<Usuario> usuarioRepository) {
            Check.Require(usuarioRepository != null, "usuarioRepository may not be null");

            this.usuarioRepository = usuarioRepository;
        }

        [Transaction]
        public ActionResult Index() {
            IList<Usuario> usuarios = usuarioRepository.GetAll();
            return View(usuarios);
        }

        [Transaction]
        public ActionResult Show(int id) {
            Usuario usuario = usuarioRepository.Get(id);
            return View(usuario);
        }

        public ActionResult Create() {
            UsuarioFormViewModel viewModel = UsuarioFormViewModel.CreateUsuarioFormViewModel();
            return View(viewModel);
        }

        [ValidateAntiForgeryToken]
        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Usuario usuario) {
            if (ViewData.ModelState.IsValid && usuario.IsValid()) {
                usuarioRepository.SaveOrUpdate(usuario);

                TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = 
					"The usuario was successfully created.";
                return RedirectToAction("Index");
            }

            UsuarioFormViewModel viewModel = UsuarioFormViewModel.CreateUsuarioFormViewModel();
            viewModel.Usuario = usuario;
            return View(viewModel);
        }

        [Transaction]
        public ActionResult Edit(int id) {
            UsuarioFormViewModel viewModel = UsuarioFormViewModel.CreateUsuarioFormViewModel();
            viewModel.Usuario = usuarioRepository.Get(id);
            return View(viewModel);
        }

        [ValidateAntiForgeryToken]
        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(Usuario usuario) {
            Usuario usuarioToUpdate = usuarioRepository.Get(usuario.Id);
            TransferFormValuesTo(usuarioToUpdate, usuario);

            if (ViewData.ModelState.IsValid && usuario.IsValid()) {
                TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = 
					"The usuario was successfully updated.";
                return RedirectToAction("Index");
            }
            else {
                usuarioRepository.DbContext.RollbackTransaction();

				UsuarioFormViewModel viewModel = UsuarioFormViewModel.CreateUsuarioFormViewModel();
				viewModel.Usuario = usuario;
				return View(viewModel);
            }
        }

        private void TransferFormValuesTo(Usuario usuarioToUpdate, Usuario usuarioFromForm) {
			usuarioToUpdate.Nome = usuarioFromForm.Nome;
        }

        [ValidateAntiForgeryToken]
        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(int id) {
            string resultMessage = "The usuario was successfully deleted.";
            Usuario usuarioToDelete = usuarioRepository.Get(id);

            if (usuarioToDelete != null) {
                usuarioRepository.Delete(usuarioToDelete);

                try {
                    usuarioRepository.DbContext.CommitChanges();
                }
                catch {
                    resultMessage = "A problem was encountered preventing the usuario from being deleted. " +
						"Another item likely depends on this usuario.";
                    usuarioRepository.DbContext.RollbackTransaction();
                }
            }
            else {
                resultMessage = "The usuario could not be found for deletion. It may already have been deleted.";
            }

            TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = resultMessage;
            return RedirectToAction("Index");
        }

		/// <summary>
		/// Holds data to be passed to the Usuario form for creates and edits
		/// </summary>
        public class UsuarioFormViewModel
        {
            private UsuarioFormViewModel() { }

			/// <summary>
			/// Creation method for creating the view model. Services may be passed to the creation 
			/// method to instantiate items such as lists for drop down boxes.
			/// </summary>
            public static UsuarioFormViewModel CreateUsuarioFormViewModel() {
                UsuarioFormViewModel viewModel = new UsuarioFormViewModel();
                
                return viewModel;
            }

            public Usuario Usuario { get; internal set; }
        }

        private readonly IRepository<Usuario> usuarioRepository;
    }
}
